package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.MessageListEntity;
import com.zw.yzk.kabu.data.network.service.MessageListService;
import com.zw.yzk.kabu.data.network.task.MessageListTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/1/12.
 */

public class MessageListRepository extends CommonRepository {

    private int totalCount;

    @Inject
    public MessageListRepository() {
        totalCount = MessageListTask.DEFAULT_MESSAGE_COUNT_PER_PAGE;
    }


    @Override
    protected Observable connectServer(Task task) {
        MessageListService service = ServiceGenerator.createService(MessageListService.class);
        MessageListTask getFansTask = (MessageListTask) addToken(task);

        if (getFansTask.start >= totalCount) {
            MessageListEntity entity = new MessageListEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.total = totalCount;

            return Observable.just(entity);
        } else {
            return service.getMessageList(
                    getFansTask.userId,
                    getFansTask.accessToken,
                    getFansTask.lastId,
                    getFansTask.size,
                    getFansTask.messageType);
        }
    }

    @Override
    protected Func1<MessageListEntity, Observable> getServerData() {
        return new Func1<MessageListEntity, Observable>() {
            @Override
            public Observable call(MessageListEntity entity) {
                totalCount = entity.result.total;
                return Observable.just(entity);
            }
        };
    }

}
